const cloud = require('wx-server-sdk')

cloud.init({
  env: "yt-active-8gnmft6y371c4f18"
})
const db = cloud.database();
const activeId = "4885635e676b67d10045012b049adf11";
async function log() {
  // 先取出集合记录总数
  const wxContext = cloud.getWXContext()
  let info = {
    hasAward: "pedding",
    forActive: activeId,
    awardLis: []
  }
  const res = await db.collection('activelog').aggregate()
  .match({
    openId: wxContext.OPENID,
    forActive: activeId
  }).limit(1).lookup({
    from: 'award',
    localField: 'forAward',
    foreignField: '_id',
    as: 'awardList',
  }).end()
  if (!res.list.length) {
    await db.collection('activelog').add({
      data: {
        openId: wxContext.OPENID,
        ...info,
        updatedAt: new Date().getTime()
      }
    })
  } else {
    info = res.list[0]
  }
  return {
    errMsg: "document.get:ok",
    data: {
      ...info
    }
  }
}
async function up(event) {
  try {
    if (event.password != 976523) {
      return {
        success: false,
        errMsg: "密码错误"
      }
    }
    const info = await db.collection('activelog').doc(event._id).get()
    if (info.data.isGet) {
      return {
        success: false,
        errMsg: "请勿重复核销"
      }
    }
    const res = await db.collection('activelog').doc(event._id).update({
      data: {
        isGet: true
      }
    })
    return {
      success: true,
      ...res
    }
  } catch (error) {
    return {
      success: false,
      errMsg: "兑换失败"
    }
  }
 
}

async function details(event) {
  const res = await db.collection('activelog').aggregate().match({
    _id: event._id,
  }).limit(1).lookup({
    from: 'award',
    localField: 'forAward',
    foreignField: '_id',
    as: 'awardList',
  }).end();
  return {
    success: true,
    data: {
      ...res.list[0]
    }
  }
}
module.exports = {
  log,
  details,
  up,
}